<template>
  <div>
    <!--面包屑导航区-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/main' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>系统管理</el-breadcrumb-item>
      <el-breadcrumb-item>密码管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片视图-->
    <el-card>
      <!--搜索与添加区域-->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input v-model="queryInfo.query" placeholder="请输入内容" clearable @clear="getPasswordList">
            <el-button slot="append" icon="el-icon-search" @click="getPasswordList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加密码</el-button>
        </el-col>
      </el-row>
      <!--用户列表区-->
      <el-table stripe border :data="passwordList" style="width: 100%">
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="cloudType" label="类型"></el-table-column>
        <el-table-column prop="cloudIp" label="访问地址"></el-table-column>
        <el-table-column prop="executeType" label="操作类型"></el-table-column>
        <el-table-column prop="username" label="用户名"></el-table-column>
        <el-table-column prop="password" label="密码">************</el-table-column>
        <el-table-column prop="out" label="是否过时"></el-table-column>
        <el-table-column prop="comment" label="描述"></el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-tooltip effect="dark" :enterable="false" content="修改" placement="top">
              <el-button type="primary" size="mini" @click="showEditDialog(scope.row.id)" icon="el-icon-edit"></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" :enterable="false" content="删除" placement="top">
              <el-button type="danger" size="mini" @click="removePasswordById(scope.row.id)" icon="el-icon-delete"></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" :enterable="false" content="查看密码" placement="top">
              <el-button type="warning" size="mini" icon="el-icon-setting" @click="showPasswordDialog(scope.row.id)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!--分页区域-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[10,20,30,40]"
        :page-size="queryInfo.pageSize"
        :total="total"
        layout="total,sizes,prev,pager,next,jumper">
      </el-pagination>
      <!--添加用户的对话框-->
      <el-dialog title="添加密码" :visible.sync="addDialogVisible" width="50%" @close="addPasswordDialogClosed">
        <!--内容主体区域 ref引用名称-->
        <el-form :model="addForm" :rules="addFormPasswords" ref="addPasswordFormRef" label-width="70px">
          <el-form-item label="类型" label-width="120px">
            <el-input v-model="addForm.cloudType"></el-input>
          </el-form-item>
          <el-form-item label="访问地址" label-width="120px">
            <el-input v-model="addForm.cloudIp"></el-input>
          </el-form-item>
          <el-form-item label="操作类型" label-width="120px">
            <el-input v-model="addForm.executeType"></el-input>
          </el-form-item>
          <el-form-item label="用户名" label-width="120px" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" label-width="120px" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="是否过时" label-width="120px">
            <el-input v-model="addForm.out"></el-input>
          </el-form-item>
          <el-form-item label="描述" label-width="120px">
            <el-input v-model="addForm.comment"></el-input>
          </el-form-item>
        </el-form>
        <!--底部按钮区域-->
        <div slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addPassword">确 定</el-button>
        </div>
      </el-dialog>
      <!--修改用户的对话框-->
      <el-dialog title="修改密码" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
        <!--内容主体区域 ref引用名称-->
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
          <el-form-item label="类型" label-width="120px" prop="text">
            <el-input v-model="editForm.cloudType"></el-input>
          </el-form-item>
          <el-form-item label="访问地址" label-width="120px" prop="text">
            <el-input v-model="editForm.cloudIp"></el-input>
          </el-form-item>
          <el-form-item label="操作类型" label-width="120px" prop="text">
            <el-input v-model="editForm.executeType"></el-input>
          </el-form-item>
          <el-form-item label="用户名" label-width="120px" prop="text">
            <el-input v-model="editForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" label-width="120px" prop="text">
            <el-input v-model="editForm.password" disabled></el-input>
          </el-form-item>
          <el-form-item label="是否过时" label-width="120px" prop="text">
            <el-input v-model="editForm.out"></el-input>
          </el-form-item>
          <el-form-item label="描述" label-width="120px" prop="text">
            <el-input v-model="editForm.comment"></el-input>
          </el-form-item>
        </el-form>
        <!--底部按钮区域-->
        <div slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editPassword">确 定</el-button>
        </div>
      </el-dialog>
      <!--获取用户密码的对话框-->
      <el-dialog title="密码" :visible.sync="passwordDialogVisible" width="50%" @close="passwordDialogClosed">
        <!--内容主体区域 ref引用名称-->
        <el-form :model="passwordForm" ref="passwordFormRef" label-width="70px">
          <el-form-item label="开发者号码" label-width="120px" prop="text">
            <el-input v-model="passwordForm.phone"></el-input>
          </el-form-item>
          <el-form-item label="验证码" label-width="120px" prop="text">
            <div style="display: flex"><el-input v-model="passwordForm.verifyCode"></el-input><img class="v_img" :src="captcha"/></div>
          </el-form-item>
        </el-form>
        <!--底部按钮区域-->
        <div slot="footer" class="dialog-footer">
          <el-button @click="passwordDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="getPassword">获取密码</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
// import { JSEncrypt } from 'jsencrypt' 每次获取密码不一致
import CryptoJS from 'crypto-js/crypto-js'

export default {
  data () {
    // 自定义验证规则: 邮箱的规则
    const checkEmail = (rule, value, callback) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        // 合法邮箱
        return callback()
      }
      callback(new Error('请输入合法的邮箱'))
    }
    const checkPhone = (rule, value, callback) => {
      // 验证手机号的正则表达式
      const regPhone = /^(0|86|17951)?(13[0-9]|15[0-9]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regPhone.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法的手机号'))
    }

    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: '',
        pageNum: 1,
        pageSize: 10
      },
      passwordList: [],
      total: 0,
      // 控制用户添加对话框
      addDialogVisible: false,
      // 添加用户的表单信息
      addForm: {
        username: '',
        password: '',
        cloudType: '',
        cloudIp: '',
        executeType: '',
        comment: '',
        out: ''
      },
      // 添加用户的校验规则
      addFormPasswords: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
          { min: 2, max: 10, message: '昵称的长度在2~10个字符之间', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        phoneNumber: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          { validator: checkPhone, trigger: 'blur' }
        ]
      },
      // 控制修改用户的对话框
      editDialogVisible: false,
      // 查询到的用户信息
      editForm: {},
      // 修改用户的校验规则
      editFormRules: {
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
          { min: 2, max: 10, message: '昵称的长度在2~10个字符之间', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        phoneNumber: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          { validator: checkPhone, trigger: 'blur' }
        ]
      },
      passwordDialogVisible: false,
      passwordForm: {
        id: '',
        phone: '',
        verifyCode: ''
      },
      captcha: ''
    }
  },
  created () {
    this.getPasswordList()
  },
  methods: {
    async getPasswordList () {
      const { data: res } = await this.$http.get('/vueShop/passwords', { params: this.queryInfo })
      // console.log(res)
      if (!res.status) return this.$message.error(res.msg)
      this.passwordList = res.data
      this.total = res.total
    },
    // 监听 pageSize 改变的事件
    handleSizeChange (newSize) {
      // console.log(newSize)
      this.queryInfo.pageSize = newSize
      this.getPasswordList()
    },
    handleCurrentChange (newPage) {
      // console.log(newPage)
      this.queryInfo.pageNum = newPage
      this.getPasswordList()
    },
    // 监听添加用户对话框关闭事件
    addPasswordDialogClosed () {
      this.$refs.addPasswordFormRef.resetFields()
    },
    // 点击按钮 添加用户
    addPassword: function () {
      this.$refs.addPasswordFormRef.validate(async valid => {
        if (!valid) return this.$message.error('验证不通过')

        // 发起添加用户的真正请求
        // 1、密码进行加密传输
        const { data: encKey } = await this.$http.post('/vueShop/api/getEncKey')
        if (!encKey.status) return this.$message.error('获取密钥钥失败')
        // const pass = this.encryptedData(this.addForm.password, 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCTS+2DWgEszCulNb+GQcVnjh2NaQ1ZJP5NYc+QxSs/zaL38NnVXYKd6NOdag5iCLkDXX4iPfXDM4nduM5QBzyyV2jaOb0H9wzrd3LfcVSds7MvElI2bQeObb2J9kr1zcagpjbfwT2GpnhwMkDy6YwTRxHZu2/R508IlZxyRrl9vQIDAQAB')
        // key值
        const key = CryptoJS.enc.Utf8.parse(encKey.data)
        // 密码
        const password = CryptoJS.enc.Utf8.parse(this.addForm.password)
        // 进行加密
        const encrypted = CryptoJS.AES.encrypt(password, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 })
        const { data: res } = await this.$http.post('/vueShop/passwords?username=' + this.addForm.username +
          '&password=' + encrypted.toString() + '&cloudType=' + this.addForm.cloudType + '&cloudIp=' +
          this.addForm.cloudIp + '&executeType=' + this.addForm.executeType +
          '&out=' + this.addForm.out + '&comment=' + this.addForm.comment)
        if (!res.status) return this.$message.error('添加密码失败')
        this.$message.success('添加密码成功')
        // 隐藏添加用户的对话框
        this.addDialogVisible = false
        // 刷新用户列表
        this.getPasswordList()
      })
    },
    // 点击展示编辑用户的对话框
    async showEditDialog (id) {
      const { data: res } = await this.$http.get('/vueShop/passwords/' + id)
      if (!res.status) return this.$message.error('查询密码详细数据失败')
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 监听修改用户对话框关闭事件
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    // 点击修改用户
    editPassword () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return this.$message.error('验证不通过')
        // 发起修改用户的真正请求
        const { data: res } = await this.$http.put('/vueShop/passwords/' + this.editForm.id +
          '?username=' + this.editForm.username + '&cloudType=' +
          this.editForm.cloudType + '&cloudIp=' + this.editForm.cloudIp + '&executeType=' + this.editForm.executeType +
          '&out=' + this.editForm.out + '&comment=' + this.editForm.comment)
        if (!res.status) return this.$message.error('修改密码失败')
        this.$message.success('修改密码成功')
        // 隐藏添加用户的对话框
        this.editDialogVisible = false
        // 刷新用户列表
        this.getPasswordList()
      })
    },
    // 点击就删除角色
    async removePasswordById (id) {
      // 这样就不需要加 async 和 await
      const confirmResult = await this.$confirm('此操作将永久删除该密码, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 确认删除 confirm 取消异常 cancel
      if (confirmResult !== 'confirm') return this.$message.info('用户取消了删除')
      const { data: res } = await this.$http.delete('/vueShop/passwords/' + id)
      if (!res.status) return this.$message.error('删除密码失败')
      this.$message.success('删除密码成功')
      this.getPasswordList()
    },
    async showPasswordDialog (id) {
      this.passwordForm.id = id
      const { data: res } = await this.$http.get('/vueShop/captcha')
      if (!res.status) return this.$message.error('获取验证码失败')
      this.captcha = res.data.image
      this.passwordDialogVisible = true
    },
    passwordDialogClosed () {
      this.$refs.passwordFormRef.resetFields()
    },
    async getPassword () {
      const { data: res } = await this.$http.post('/vueShop/passwords/' + this.passwordForm.id + '/phone/' + this.passwordForm.phone + '/verifyCode/' + this.passwordForm.verifyCode)
      if (!res.status) return this.$message.error('获取密码失败')
      this.$message.success('您的密码是：' + res.data)
      this.passwordDialogVisible = false
    }
    // 加密
    // encryptedData (data, publicKey) {
    //   // 私钥 和后端沟通写死了  公钥加密 私钥解密
    //   // 新建JSEncrypt对象
    //   const encryptor = new JSEncrypt()
    //   // 设置公钥
    //   encryptor.setPublicKey(publicKey)
    //   // 加密数据
    //   return encryptor.encrypt(data)
    // }
  }
}
</script>

<style lang="less" scoped>

</style>
